package handle

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"website/model"
	"website/utils"
)

func CreateContactInfo(c *gin.Context) {
	var ct model.Contact
	var m model.Managers
	if err := c.ShouldBind(&ct); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}
	if len(ct.PhoneNumber) != 0 {
		if !utils.VerifyMobileFormat(ct.PhoneNumber) {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"message": "手机格式有误，请输入正确的手机号！",
			})
			return
		}
	}
	if !utils.VerifyEmailFormat(ct.Email) {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": "邮箱格式有误，请输入正确的邮箱！",
		})
		return
	}
	if err := ct.CreateContactInfo(); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}
	mails, err := m.FetchSingleManagers(true)
	if err != nil {
		log.Println("获取具备接收邮件的后台用户失败！")
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}
	sendMailErrInfo := "发送成功"
	if len(mails) != 0 {
		if err := utils.SendMail(
			ct.LastName,
			ct.FirstName,
			ct.Email,
			ct.PhoneNumber,
			ct.Organization,
			ct.Desc,
			mails); err != nil {
			log.Println("error:", err.Error())
			sendMailErrInfo = "邮件发送失败 " + err.Error()
		}
	} else {
		log.Println("没有找到邮件接收人!")
		sendMailErrInfo = "没有找到邮件接收人！"
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": "创建状态：用户信息提交成功! 邮件发送状态：" + sendMailErrInfo,
	})
}

func FetchAllContactInfo(c *gin.Context) {
	var ct model.Contact
	res, err := ct.FetchAllContactInfo()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": "success",
		"results": res,
	})
}

func FetchSingleContactInfo(c *gin.Context) {
	var ct model.Contact
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	res, err := ct.FetchSingleContactInfo(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    1,
		"message": "success",
		"results": res,
	})
}
